//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using ConfigurationWizard.Controls;
using ConfigurationWizard.Configuration;
using System.Configuration;
using ConfigurationWizard.Setup;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Threading;

namespace ConfigurationWizard
{
    public partial class Progress : UserControl
    {
        private Collection<Task> tasks;
        private BackgroundWorker worker;
        public event EventHandler<EventArgs> OperationFailed;
        public event EventHandler<EventArgs> OperationCompleted;

        public Progress()
        {
            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += new DoWorkEventHandler(ProcessTaks);
            worker.ProgressChanged += new ProgressChangedEventHandler(ProcessTaskStatusUpdate);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ProcessTasksCompleted);
            
            InitializeComponent();
            LoadTasks();
        }

        void ProcessTasksCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (OperationCompleted != null)
                OperationCompleted(this, null);
            
            if(this.Parent != null)
                ((Shell)this.Parent.Parent).nextButton.Focus();

        }

        void ProcessTaskStatusUpdate(object sender, ProgressChangedEventArgs e)
        {
            TaskProgress progress = (TaskProgress)e.UserState;
            TaskViewControl control = (TaskViewControl)componentsPanel.Controls[progress.CurrentTaskIndex];
            Task currentTask = tasks[progress.CurrentTaskIndex];
            if (progress.CurrentTaskIndex == this.componentsPanel.Controls.Count - 1)
            {
                this.installationProgressBar.Value = 100;
            }
            else
            {
                this.installationProgressBar.Value += e.ProgressPercentage;
            }

            if (!progress.Completed)
            {
                control.SetActive();
                this.installProgressLabel.Text = string.Format(CultureInfo.CurrentCulture, "Status: {0}", currentTask.Description);
            }
            else
            {
                if (progress.Success)
                {
                    control.SetCompleted();
                    this.installProgressLabel.Text = "Setup completed";
                }
                else 
                {
                    control.SetFailed();
                    worker.CancelAsync();
                    for (int i = progress.CurrentTaskIndex; i >= 0; i--)
                    {
                        this.installationProgressBar.Value -= 2*e.ProgressPercentage;
                        Thread.Sleep(200);
                    }

                    if (OperationFailed != null)
                        OperationFailed(this, null);
                }
            }
        }

        private void LoadTasks()
        {
            SetupSection section = (SetupSection)ConfigurationManager.GetSection("setup");
            SetupConfigurationReader reader = new SetupConfigurationReader(section);
            this.tasks = reader.GetTasksForThisOS();            
        }

        void ProcessTaks(object sender, DoWorkEventArgs e)
        {
            ExecuteTasks();
        }

        private void ExecuteTasks()
        {
            int numberOfTasks = componentsPanel.Controls.Count;
            int progressIncrement = 50 / numberOfTasks;

            for (int i = 0; i < numberOfTasks ; i++)
            {
                if (worker.CancellationPending)
                    return;
                
                TaskProgress progress = new TaskProgress(i, false, false);
                worker.ReportProgress(progressIncrement, progress);
                Task task = tasks[i];
                bool success = task.Execute();
                progress = new TaskProgress(i, true, success);
                worker.ReportProgress(progressIncrement, progress);
            }
        }

        private void Progress_Load(object sender, EventArgs e)
        {
            ((Shell)this.Parent.Parent).WizardCanceled += new EventHandler<EventArgs>(OnWizardCancelled);
            int top = 0;
            for (int i = 0; i < tasks.Count; i++)
            {
                Task task = tasks[i];
                TaskViewControl control = new TaskViewControl(task.Description);
                control.Top = top;
                control.Width = componentsPanel.Width - 30;
                componentsPanel.Controls.Add(control);
                top += control.Height;
            }
            worker.RunWorkerAsync();
        }

        void OnWizardCancelled(object sender, EventArgs e)
        {
            worker.CancelAsync();
        }
    }

    class TaskProgress
    {
        private int currentTaskIndex;
        private bool completed;
        private bool success;

        public TaskProgress(int currentTaskIndex, bool completed, bool success)
        {
            this.currentTaskIndex = currentTaskIndex;
            this.completed = completed;
            this.success = success;
        }

        public int CurrentTaskIndex
        {
            get 
            {
                return this.currentTaskIndex;
            }
        }

        public bool Completed
        {
            get 
            {
                return completed;
            }
        }

        public bool Success
        {
            get 
            {
                return success;
            }
        }
    }
}
